package com.controller;

import com.Interceptor.FailInterceptor;
import com.alibaba.fastjson.JSON;
import com.config.SolrConfiguration;
import com.model.A;
import com.model.Member;
import com.services.MemberServices;
import com.utils.RedisUtil;
import com.utils.UUIDGenerator;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.beans.DocumentObjectBinder;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


@RequestMapping("/index")
@Controller
public class IndexController {


    @Autowired RedisUtil redisUtil;

    @Autowired
    MemberServices memberServices;

    @Autowired private SolrConfiguration solrClient;

    //private  SolrClient solrClient = new HttpSolrClient.Builder("http://172.16.5.108:8081/solr/index.html#/member").build();


    @FailInterceptor
    @RequestMapping("/")
    String hello() {
        return "redirect:index/index";
    }


    @FailInterceptor
    @RequestMapping("/index")
    @Cacheable(value = "indexqq")
    public String index(Model model){
        System.out.println("进入了方法");
        return "shouye";
    }

    @FailInterceptor
    @RequestMapping("/shouye")
    public String shouye(Model model){
        model.addAttribute("dtsj","");
        return "shouye";
    }






    @FailInterceptor
    @RequestMapping("/cleanIndex")
    @ResponseBody
    public String cleanIndexq(){
            return "Success!!";
    }



    @FailInterceptor
    @RequestMapping("/login")
    public String login(){

        return "login2";
    }

    @RequestMapping("/yzq")
    public String yzq(Model model, String hhh){

        model.addAttribute("dtsj",hhh);

        return "yzq";
    }
    @FailInterceptor
    @RequestMapping("/qwe")
    public String qwe(Model model, String hhh){
        return "qwe";
    }


    @FailInterceptor
    @RequestMapping("/fileupload")
    @ResponseBody
    public String fileupload(@RequestParam(value = "excelfiles", required = true)MultipartFile excel){
        try {
            String originalFilename = excel.getOriginalFilename();
            String contentType = excel.getContentType();
            File file=new File("/home/yzq/Desktop/excel",originalFilename);
            excel.transferTo(file);
            InputStream inputstream=new FileInputStream(file);
            Workbook workbook = null;// 一个workbook对象，就是一个Excel文件
            Sheet sheet=null;// sheet页，因excel总有多个sheet页，需要判断具体取值哪一个
            Row row1 = null;// Sheet页数中的某一行
            int colNum = 0;// Sheet总行数
            // 判断文件是什么格式 2003/2007 根据版本不同 处置对象也不同
            if (originalFilename.endsWith(".xls")) {
                workbook = new HSSFWorkbook(inputstream);// Excel 2003
            } else if (originalFilename.endsWith(".xlsx")) {
                workbook = new XSSFWorkbook(inputstream);// Excel 2007
            } else {
                return null;
            }
            sheet= workbook.getSheetAt(0);
            Row title = sheet.getRow(0);//标题
            int lieNum = sheet.getRow(0).getPhysicalNumberOfCells();
            int hangNum = sheet.getLastRowNum();
            List<A> list=new ArrayList<A>();
            for (int i=1;i<=hangNum;i++){
                Row row = sheet.getRow(i);
                A a=new A();
                int rowNum = row.getRowNum();
                for (int j=0;j<lieNum;j++){
                    Cell cell1 = title.getCell(j);
                    Cell cell = row.getCell(j);
                    String titlecell = cell1.getStringCellValue();
                    if (("id").equals(titlecell)){
                        a.setId(titlecell);
                    }else if (("name").equals(titlecell)){
                        a.setName(titlecell);
                    }else if (("sex").equals(titlecell)){
                        a.setSex(titlecell);
                    }else if (("age").equals(titlecell)){
                        a.setAge(titlecell);
                    }else if (("phone").equals(titlecell)){
                        a.setPhone(titlecell);
                    }
                }
                list.add(a);
            }
            return JSON.toJSON(list).toString();
        } catch (IOException e) {
            e.printStackTrace();
            return "error";
        }
    }









    @FailInterceptor
    @ResponseBody
    @RequestMapping("/testsolr")
    public String testsolr() throws IOException, SolrServerException {

        Member member = new Member();
        member.setId(UUIDGenerator.generate());
        member.setPhone("13128892235");
        member.setPassword("qwe123");
        member.setNickname("杨子强");
        member.setMobile("13128892235");
        DocumentObjectBinder binder = new DocumentObjectBinder();
        SolrInputDocument doc = binder.toSolrInputDocument(member);

        return "";
    }


    @RequestMapping("/testSolr")
    @ResponseBody
    public String testSolr(String qname,String qvalue){
        String solrurl="http://localhost:8081/solr/index.html";
        HttpSolrClient solrClient = new HttpSolrClient.Builder(solrurl).build();
        SolrQuery solrQuery = new SolrQuery();
        //solrQuery.set(qname,qvalue);
        solrQuery.set("q", "title:\"国家\"");
        solrQuery.setStart(0);
        solrQuery.setRows(10);
        try {
            QueryResponse queryResponse = solrClient.query("member", solrQuery);
            SolrDocumentList solrDocumentList= queryResponse.getResults();
            System.out.println("总共查询到："+solrDocumentList.getNumFound()+"条记录");
            System.out.println("查询时间："+queryResponse.getQTime()+"毫秒");
            for(Iterator<SolrDocument> i = solrDocumentList.listIterator(); i.hasNext();){
                SolrDocument sd=i.next();
                System.out.print("id:"+sd.getFieldValue("id"));
                System.out.println(";title:"+sd.getFieldValue("title"));
            }
        }catch (Exception ex){
            ex.printStackTrace();

        }
        return "";

    }


 /*  public void addDocument() throws Exception {

        Member member = new Member();
        member.setId("qwe123");
        member.setMobile("13128892235");
        member.setNickname("杨子强");
        member.setPassword("adminqwe123");
        member.setPhone("13128892235");*//**//*
        DocumentObjectBinder documentObjectBinder = new DocumentObjectBinder();
       // SolrInputDocument solrInputDocument =documentObjectBinder.toSolrInputDocument(member);
//        solrClient.add(solrInputDocument);
        List<OrderNew> orderNews = memberServices.finList();
        solrClient.addBeans(orderNews);
        solrClient.commit();
    }
*/












   /* public <T>List<T> findBysolrQuery(String solrQury,Class<T> clazz) {
        SolrQuery solrQuery = new SolrQuery();
        solrQuery.setQuery(solrQury);
        QueryResponse queryResponse = null;
        try {
            queryResponse = solrClient.getSolrClient().query(solrQuery);
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<T> beans = queryResponse.getBeans(clazz);
        return beans;
    }*/

    }


    /**
     * 查出所有document
     * @param clazz
     * @param <T>
     * @return
     *//*
    public <T>List<T> findDocuments(Class<T> clazz){
        return  this.findBysolrQuery("*:*",clazz);
    }

    *//**
     * 根据id查询
     * @param id
     * @param clazz
     * @param <T>
     * @return
     * @throws IOException
     * @throws SolrServerException
     *//*
    public <T>T findByid(String id,Class<T> clazz) throws IOException, SolrServerException {
        DocumentObjectBinder documentObjectBinder= new DocumentObjectBinder();
        SolrDocument solrDocument= solrClient.getById(id);
        return  solrDocument==null?null:documentObjectBinder.getBean(clazz,solrDocument);
    }*/







